// pages/goods/detail.js
const wxParse = require('../../vendor/wxParse/wxParse')
const app = getApp()
// let timer = null
Page({

    data: {
        isSpec: false,
        num: 1,
        currentSku: 0,
        cartNum: 0,
        sharePop: false,
        poster: false,
        sku: [],
        hidden_poster: true
    },

    onLoad: function(options) {
        app.share(options.pmid)
        this.setData(options)
        if (options.share) {
            this.setShareStorage(options)
        }
        wx.showLoading({
            title: '加载中...',
        })
        this.loadData()
        // this.loadSupermarket()
        app.loadCart()
    },
    // onHide(){
    //     clearInterval(timer)
    // },
    // onUnload(){
    //     clearInterval(timer)
    // },
    //分享进来
    setShareStorage(options) {
        wx.setStorage({
            key: 'location',
            data: {
                lng: options.lng,
                lat: options.lat
            },
        })
        wx.setStorage({
            key: 'cid',
            data: options.cid,
        })
    },
    loadData() {
        let {
            cid = '', goods_id = '', currentSku = 0, skuId = '', cart_id = ''
        } = this.data
        if (!cid || !goods_id) {
            return
        }
        app.http.get('supermarket/detail', {
            data: {
                cid: cid,
                goods_id: goods_id,
            }
        }).then(res => {
            if (res.data.sku.length != 0) {
                if (cart_id) {
                    res.data.sku.map((o, index) => {
                        if (o.cart_id == cart_id) {
                            currentSku = index
                        }
                    })
                }
                skuId = res.data.sku[currentSku].id //默认规格id
            }
            this.setData(Object.assign({
                skuId,
                currentSku,
            }, res.data))
            wxParse.wxParse("content", "html", this.data.content, this, 30)
            wx.hideLoading()
            this.totalPrice()
            // let data = res.data
            // let reg = /^(\d{3})\d*(\d{4})$/
            // data.fmt_mobile = data.address.mobile.replace(reg, '$1****$2')
            // data.stockStatus = parseInt(data.stock) > 0
            // if (data.stockStatus) { //是否有库存
            //     data.pre_status = this.time_range(data.group_time.group_start_time, data.group_time.group_end_time) //是否在在售期间
            // }
            // // data.fmt_address = this.hidden(data.address.address, 10)
            
            // this.loadCode()
        }).catch(err => {
            wx.hideLoading()
        })
    },
    loadSupermarket() {
        app.http.post('shopping-cart/quantity', {
            data: {
                cid: this.data.cid
            }
        }).then(res => {
            this.setData({
                cart_num: parseInt(res.data)
            })
        })
    },
    // loadCart() {
    //     app.http.post('shopping-cart/quantity', {
    //         data: {
    //             cid: this.data.cid
    //         }
    //     }).then(res => {
    //         this.setData({
    //             cart_num: parseInt(res.data)
    //         })
    //     })
    // },
    loadCode() {
        app.http.post('goods/xcx-code', {
            data: {
                goods_id: this.data.goods_id,
                cid: this.data.cid
            }
        }).then(res => {
            this.setData({
                codeQR: res.data
            })
        })
    },
    hidden(str, frontLen) {
        var xing = ''
        for (var i = 0; i < 4; i++) {
            xing += '*';
        }
        return str.substring(0, frontLen) + xing
    },
    /**
     * 商品规格弹出
     * specType 1加入购物车 2直接购买
     */
    selectSpec(e) {
        let specType = e.currentTarget.dataset.type
        this.setData({
            specType,
            isSpec: !this.data.isSpec
        })
    },
    isShare() {
        this.setData({
            sharePop: !this.data.sharePop
        })
    },
    isPoster() {
        this.setData({
            poster: !this.data.poster
        })
    },
    /**
     * 数量加减
     */
    num_plus: function() {
        let num = this.data.num + 1
        this.updateNum(num)
    },

    num_minus: function() {
        let num = this.data.num - 1
        this.updateNum(num)
    },
    updateNum: function(num) {
        if (num < 1) num = 1
        if (num > this.data.max_amount) {
            num = this.data.max_amount
        }
        this.setData({
            num,
        })
    },
    /**
     * 倒计时
     */
    // time_range(beginTime, endTime) {
    //     let this_date = new Date();
    //     let today = this_date.getFullYear() + "/" + (this_date.getMonth() + 1) + "/" + this_date.getDate();
    //     let begin_time = new Date(today + " " + beginTime);
    //     let end_time = new Date(today + " " + endTime);
    //     if (begin_time.getTime() >= end_time.getTime()) {
    //         end_time.setDate(this_date.getDate() + 1)
    //     }
    //     if (this_date.getTime() >= begin_time.getTime() && this_date.getTime() <= end_time.getTime()) { //距离结束
    //         this.countDown(end_time.getTime())
    //         console.log("当前时间是：" + this_date + "，在该时间范围内！");
    //         return true
    //     } else { //当前时间大于 距离开始  begintime+1
    //         if (this_date.getTime() > begin_time.getTime()) {
    //             begin_time.setDate(this_date.getDate() + 1)
    //         }
    //         this.countDown(begin_time.getTime())
    //         console.log("当前时间是：" + this_date + "，不在该时间范围内！");
    //         return false;
    //     }
    // },
    // countDown: function(end_time) {
    //     if (!end_time || parseInt(this.data.stock) <= 0) {
    //         return
    //     }
    //     end_time = end_time / 1000
    //     let this_date = new Date().getTime() / 1000;
    //     let times = 0;
    //     if (end_time > this_date) { //结束
    //         times = end_time - this_date
    //         console.log(end_time, '结束')
    //     } else {
    //         times = this_date - end_time
    //         console.log(end_time, '开始')
    //     }
    //     timer = setInterval(() => {
    //         let day = 0,
    //             hour = 0,
    //             minute = 0,
    //             second = 0;
    //         day = Math.floor(times / (60 * 60 * 24));
    //         hour = Math.floor(times / (60 * 60)) - (day * 24);
    //         minute = Math.floor(times / 60) - (day * 24 * 60) - (hour * 60);
    //         second = Math.floor(times) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);

    //         day = day <= 0 ? '' : day <= 9 ? '0' + day + '天' : day + '天'
    //         hour = hour <= 9 ? '0' + hour + '时' : hour + '时'
    //         minute = minute <= 9 ? '0' + minute + '分' : minute + '分'
    //         second = second <= 9 ? '0' + second + '秒' : second + '秒'

    //         this.setData({
    //             remain_time: day + hour + minute + second,
    //         })
    //         times--;

    //         if (times <= 0) {
    //             clearInterval(timer)
    //             this.setData({
    //                 pre_status: this.time_range(this.data.group_time.group_start_time, this.data.group_time.group_end_time)
    //             })
    //         }
    //     }, 1000);
    // },
    /**
     * 选择商品规格
     */
    selectSku(evt) {
        let index = evt.currentTarget.dataset.index
        this.setData({
            currentSku: index,
            skuId: this.data.sku[index].id,
        })
        this.totalPrice()
    },

    //计算总价
    totalPrice() {
        let sku_price = this.data.sku[this.data.currentSku].price
        let sell_price = this.data.sell_price_num
        this.setData({
            selected_price: parseFloat(sku_price) + parseFloat(sell_price)
        })
    },
    /**
     * 加入购物车
     */
    joinCart(e) {
        let jtype = e.currentTarget.dataset.type
        let {
            goods_id = '', num = 1, skuId = 0, cid = '', cartNum = 0,
        } = this.data
        let user = wx.getStorageSync('user')
        if (!user || !goods_id || !cid) return
        wx.showLoading({
            title: '请稍等...',
        })

        let params = {
            goods_id: goods_id,
            quantity: num,
            sku_id: skuId,
            type: 3, //1社区 2核销 3超市
        }
        app.addToCart(params).then(res => {
            cartNum += num
            this.setData({
                isSpec: false,
                cartNum,
            })
            if (jtype == 2) { //购买
                let arr = [res]
                app.okParam = {
                    type: this.data.order_type,
                    goods_info: JSON.stringify(arr),
                }
                wx.redirectTo({
                    url: '/pages/order/order-ok?goods_type=' + this.data.order_type,
                })
                return
            }
            wx.showToast({
                icon: 'none',
                title: '添加购物车成功,等你来买',
            })
        }).catch(err => {
            wx.hideLoading()
        })

    },
    onShareAppMessage: function(e) {
        if (e.from === 'button') {
            this.isShare()
        }
        let location = wx.getStorageSync('location')
        let params = {
            cid: this.data.cid,
            goods_id: this.data.goods_id,
            lng: location.lng,
            lat: location.lat,
            share: 1
        }
        let imageUrl = this.data.forward_image
        return app.getShareObj(this.data.name, params)
    },


    // 生成海报
    saveImageToPhotosAlbum: function() {
        wx.showLoading({
            title: '生成海报中...'
        })
        var that = this;
        //设置画板显示，才能开始绘图
        that.setData({
            canvasHidden: false,
            sharePop: false,
        })

        function download(url) {
            return new Promise(resolve => {
                wx.downloadFile({
                    url: url,
                    success: res => {
                        resolve(res.tempFilePath);
                    }
                })
            })
        }
        var unit = app.scrollWidth / 375
        var ctx = wx.createCanvasContext('poster')
        ctx.setFillStyle('#fff')
        ctx.font = "10px PingFang SC"
        ctx.fillRect(0, 0, unit * 250, unit * 400)
        // 背景
        download(that.data.codeQR).then(r => {
            ctx.drawImage(r, unit * 25, unit * 313, unit * 77, unit * 77);
            ctx.translate(0.5, 0.5);
            ctx.setLineWidth(1)
            ctx.moveTo(unit * 48, unit * 42)
            ctx.lineTo(unit * 203, unit * 42)
            ctx.setStrokeStyle('#ebebeb')
            ctx.stroke()
            return download('https://img.zhxcxmall.com/ll/logo-row.png')
        }).then(r => {
            ctx.drawImage(r, unit * 87, unit * 14, unit * 78, unit * 23);
            return download('https://img.zhxcxmall.com/ll/share-pop-bg.png')
        }).then(r => {
            ctx.drawImage(r, 0, 0, unit * 250, unit * 400);
            return download(that.data.cover_image)
        }).then(r => {
            ctx.drawImage(r, unit * 50, unit * 50, unit * 150, unit * 150);
            var name = that.data.name //标题
            ctx.setTextAlign('center')
            ctx.setFontSize(12)
            ctx.setFillStyle("#111")
            var canvasWidth = unit * 180; //文字显示的宽度
            var initHeight = unit * 220; //绘制字体距离canvas顶部初始的高度
            that.drawText(ctx, name, initHeight, canvasWidth, unit);

            var price = that.data.mall_price //价格
            var priceWidth = parseInt(ctx.measureText(price).width)
            ctx.setTextAlign('center')
            ctx.setFontSize(14)
            ctx.setFillStyle("#ff5400")
            ctx.fillText(price, unit * 125 - unit * 25, unit * 254)

            var icon = '¥'
            ctx.setFontSize(8) //¥
            ctx.setFillStyle("#ff5400")
            ctx.fillText(icon, (unit * 125 - unit * 25) - (priceWidth / 2) - unit * 5, unit * 254)

            var g_unit = '/' + that.data.unit
            ctx.setFontSize(10) //单位
            ctx.setFillStyle("#ff5400")
            ctx.fillText(g_unit, (unit * 125 - unit * 25) + (priceWidth / 2) + unit * 10, unit * 254)

            var market = '¥' + that.data.market_price
            var marketWidth = parseInt(ctx.measureText(market).width)
            ctx.setFontSize(8) //市场价
            ctx.setFillStyle("#999")
            ctx.fillText(market, (unit * 125 - unit * 10) + (priceWidth / 2) + unit * 25, unit * 254)

            ctx.beginPath()
            ctx.translate(0.1, 0.1);
            ctx.setLineWidth(1)
            ctx.moveTo((unit * 125) + (priceWidth / 2), unit * 251)
            ctx.lineTo((unit * 125) + (priceWidth / 2) + marketWidth - unit * 10, unit * 251)
            ctx.setStrokeStyle('#999')
            ctx.stroke()
            ctx.restore()

            return download('https://img.zhxcxmall.com/ll/fillet-bg.png')
        }).then(r => {
            ctx.drawImage(r, unit * 87, unit * 266, unit * 76, unit * 15);
            var price = '已有' + that.data.sell_num + '人参团' //价格
            ctx.setTextAlign('center')
            ctx.setFontSize(7)
            ctx.setFillStyle("#fff")
            ctx.fillText(price, unit * 125, unit * 274)

        }).then(r => {
            ctx.beginPath()
            ctx.translate(0.1, 0.1);
            ctx.setLineWidth(1)
            ctx.moveTo(unit * 10, unit * 306)
            ctx.lineTo(unit * 240, unit * 306)
            ctx.setStrokeStyle('#ebebeb')
            ctx.stroke()

        }).then(r => {
            ctx.setFontSize(10)
            ctx.setFillStyle("#111")
            ctx.fillText('长按识别小程序二维码', unit * 170, unit * 349)

            ctx.setFontSize(8)
            ctx.setFillStyle("#999")
            ctx.fillText('好货要和朋友一起分享', unit * 172, unit * 365)

        }).then(r => {
            ctx.draw(false, function() {
                wx.hideLoading()
                that.setData({
                    poster: true,
                })
            })

        })
    },
    drawText: function(ctx, str, initHeight, canvasWidth, unit) {
        var lineWidth = 0;
        var lastSubStrIndex = 0; //每次开始截取的字符串的索引
        for (let i = 0; i < str.length; i++) {
            lineWidth += ctx.measureText(str[i]).width;
            if (lineWidth > canvasWidth) {
                ctx.fillText(str.substring(lastSubStrIndex, i), unit * 125, initHeight); //绘制截取部分
                initHeight += unit * 15; //两行之间字体的高度
                lineWidth = 0;
                lastSubStrIndex = i;
            }
            if (i == str.length - 1) { //绘制剩余部分
                ctx.fillText(str.substring(lastSubStrIndex, i + 1), unit * 125, initHeight);
            }
        }
    },
    savePoster() {
        var that = this
        var unit = app.scrollWidth / 375
        wx.showLoading({
            title: '保存中',
        })
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: unit * 250,
            height: unit * 400,
            destWidth: unit * 1250,
            destHeight: unit * 2000,
            quality: 1,
            canvasId: 'poster',
            success: res => {
                that.setData({
                    scope: false
                })
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: (res) => {
                        wx.showModal({
                            title: '温馨提示',
                            content: '商品海报已保存到手机相册',
                            showCancel: false,
                            confirmColor: '#ff5400'
                        })
                        wx.hideLoading()
                        that.setData({
                            canvasHidden: true,
                            poster: false,
                        })
                    },
                    fail: (err) => {
                        console.log(err, 'xxxxxxxxxx');
                        wx.hideLoading()
                        wx.showToast({
                            title: '保存失败，请稍后再试',
                            icon: 'none'
                        })
                        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                            that.setData({
                                scope: true
                            })
                        }
                    }
                })
            }
        })
    }
})